<?php

namespace App\Services\System;

use App\Models\System\Role as SystemRole;
use Illuminate\Support\Facades\DB;

/**
 * 角色服务类
 * @package App\Services
 */
class Role
{
    /**
     * 获取角色列表
     * @return mixed
     */
    public function getRoleList()
    {
        $roleList = SystemRole::orderBy('order_num','ASC')->orderBy('role_id','ASC')->get();
        return $roleList ? $roleList->toArray() : [];

    }
    /**
     * 获取所有角色列表，并附加角色拥有权限数据
     * @return array
     */
    public function getAllRoleWithPermList()
    {
        $sql = 'select `name`, `sys_permission_roles`.`perm_id` as `perm_id`, `sys_permission_roles`.`role_id` as `role_id` from `sys_roles` inner join `sys_permission_roles` on `sys_roles`.`role_id` = `sys_permission_roles`.`role_id`';
        $roleList = DB::select($sql);
        return $roleList;
    }
    /**
     * 保存角色数据
     * @param array $postData
     * @return bool
     */
    public function saveData($postData = [])
    {
        DB::beginTransaction();
        try{
            $roleId = $postData['role_id'] ?? 0;
            if ($roleId){
                $roleModel = SystemRole::find($roleId);
            }else{
                $roleModel = new SystemRole;
            }
            $roleModel->parent_id = $postData['parent_id'] ?? 0;
            $roleModel->name = $postData['name'] ?? '';
            $roleModel->display_name = $postData['display_name'] ?? '';
            $roleModel->perm_ids = $postData['perm_ids'] ?? [];
            $roleModel->description = $postData['description'] ?? '';
            $roleModel->order_num = (int) $postData['order_num'] ?? 0;
            $roleModel->save();

            $roleModel->permissions()->sync($roleModel->perm_ids);
            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            throw new \Exception($e->getMessage());
        }
        //刷新权限数据
        (new \App\Services\System\Permission())->getCachePermList(true);
        return true;
    }

    /**
     * 获取角色数据
     * @param $roleId
     * @return mixed
     */
    public function get($roleId)
    {
        $roleData = SystemRole::findOrFail($roleId);
        return $roleData;
    }
    /**
     * 删除角色
     * @param $roleIds
     * @return int
     */
    public function del($roleIds)
    {
        $roles = SystemRole::query()->findMany($roleIds);
        if ($roles->isNotEmpty()){
            foreach ($roles as $role){
                $role->delete();
            }
        }
        return true;
    }
}
